package com.six.order.service.impl;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.six.core.entity.Order;
import com.six.core.entity.PayLog;
import com.six.core.vo.GoodsNumUpdateVo;
import com.six.order.dao.OrderMapper;

import com.six.order.dao.PayLogMapper;
import com.six.order.dao.WeiXinMapper;
import com.six.order.feign.GoodsFeign;
import com.six.order.vo.PayInfoVo;
import com.six.order.vo.PayStatusEnum;
import com.six.order.vo.dto.PayOrderVo;
import com.six.order.vo.dto.PayResultDTO;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author:zzh
 * @create: 2023-03-07 18:40
 * @Description:
 */
@Service
public class PayServiceImpl {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private WeiXinMapper weiXinMapper;

    @Autowired
    private PayLogMapper payLogMapper;

    @Autowired
    private GoodsFeign goodsFeign;

    @Value("2021000120616072")
    private String appId;

    @Value("MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCvtAS1xkp5MtdF7gpm3cLA86NyYwX1T1u2xFFLY+cRyEF4nb9/1laiVRTvQ4ZZ5bRtZBJ/5ViV4C4p+y4Du0yIgcDDrMXhVR57AtqRJTDmIaUyjr4hqCFH/ZGzKfCJ5HCSweJ3QPE3hfht537j4r3TsmYgPfEsje6TeB6lmFd7CyKQbEyq7NBYI12eRp+qq6RcgsfmxlXbz+7F84XckNzZQKB4l6UoLHv21s271v5GhaUsM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n6DnG4dND9h6y41opWQOwe/PF0WVQTTUaiydO12XDz55ESoy7+cr37DaJh0OGd477GrHKPc6Xw0+PiPc0hKmbEox33ECgYEAwWRckTUfQcD8FtvxPgoadQXZHSo5mdSU8WNiF2FhaoqGNPxeBzG+lWX0asE/DswjSMyD7k1Q2AsqOlpHdguqOwbXFYleJ8Ryl31Yd8I+Q8nzSdNzA5uNLD0cveZ0OalSklLwFFyF/Z+mVsF4lfH7wXAL0sLifE8OSwu6ZngjDSw=")
    private String privateKey;

    @Value("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmAs4npO87VlRMizg8JLQ+Ui4BNCd3X4Vzb+9KvtMf417mahztPRgb/R3pnl2VD4Pp7Ks/2RUovNHnyOG4gUFLp2Kpje1JVO+tyKDUb+nGtZac1ikK7Z0km2hkUtHs72ECrS71pH/or6YF5Cw4FJ2/Em6aKUmJvHfUUUUmkOpaYLk6T8UjWvD/bIVt1eF4S1dEfZ+mUu3m4XsuGQhTBadh5p2S8YeWiT+MObmzDNZpG2XfLBgelPgfWSG8vL0px0A1X/xKIqUX/7cRdHn7z+IdOV9EWlpQwd7OTgeDeuX2II4AwjtYO9Gpuo5ilsv0XcuzJaRQRHxtcSVD+LH240B8QIDAQAB")
    private String publicKey;

    @Value("https://openapi.alipaydev.com/gateway.do")
    private String gateway;

    private AlipayClient alipayClient;

    @PostConstruct
    public void init() {
        alipayClient = new DefaultAlipayClient(gateway,
                appId, privateKey, "json", "utf-8", publicKey, "RSA2");
    }

    //获取订单信息生成二维码
    public PayInfoVo getPayInfo(String orderId) {
        //根据订单号查询到订单信息
        List<PayOrderVo> payOrderVos = orderMapper.payOrder(orderId);

        //计算订单价格总和  拼接商品名称  拼接店铺名称
        double sumPrice=0;
        StringBuilder goodsName=new StringBuilder();
        for (PayOrderVo payOrderVo : payOrderVos) {
            sumPrice += payOrderVo.getPrice();
            goodsName.append(payOrderVo.getGoodsName()+",");
        }
        System.out.println("====");
        String newGoodsName = goodsName.substring(0, goodsName.length()-1);

        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        request.setBizContent("{" +
                "    \"out_trade_no\":\"" + orderId + "\"," +//商户订单号
                "    \"total_amount\":\"" + sumPrice + "\"," +
                "    \"subject\":\"" + newGoodsName + "当面付" + "\"," +
                "    \"store_id\":\"00100\"," + // (必填) 商户门店编号，通过门店号和商家后台可以配置精准到门店的折扣信息，详询支付宝技术支持
                "    \"timeout_express\":\"5m\"}");//订单允许的最晚付款时间

        AlipayTradePrecreateResponse response = null;
        String qrCode = "";
        try {
            response = alipayClient.execute(request);
            if (!response.isSuccess()) {
                PayInfoVo payInfoVo = new PayInfoVo();
                payInfoVo.setUrl("生成订单失败");
                return payInfoVo;
            }
            qrCode = response.getQrCode();
        } catch (AlipayApiException e) {
            PayInfoVo payInfoVo = new PayInfoVo();
            payInfoVo.setUrl(e.getErrMsg());
            return payInfoVo;
        }

        PayInfoVo payInfoVo = new PayInfoVo();
        payInfoVo.setOrderId(orderId);
        payInfoVo.setGoodsName(goodsName.toString());
        payInfoVo.setUrl(qrCode);
        payInfoVo.setPrice(sumPrice);
        return payInfoVo;


    }

    // 根据orderId获取支付状态
    public PayResultDTO getPayStatus(String orderId) {

        //创建API对应的request类
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizContent("{" +
                "    \"out_trade_no\":\"" + orderId + "\"}");
        AlipayTradeQueryResponse response = null;
//        Order order = new Order();
//        order.setOrderId(orderId);
        PayResultDTO payResultDTO = new PayResultDTO();
        try {
            response = alipayClient.execute(request);
            if (!response.isSuccess()) {
                // 获取支付信息失败
                payResultDTO.setStatus(PayStatusEnum.WAIT_SCANNED.getCode());
                payResultDTO.setMsg("等待扫码");
                return payResultDTO;
            }
            //payResultDTO.setThirdPartId(response.getTradeNo());
            switch (response.getTradeStatus()) {
                case "WAIT_BUYER_PAY":
                    payResultDTO.setStatus(PayStatusEnum.UN_PROCESSED.getCode());
                    payResultDTO.setMsg("已扫码，等待用户支付");
                    break;
                case "TRADE_CLOSED":
                    payResultDTO.setStatus(PayStatusEnum.SHIPPING.getCode());
                    payResultDTO.setMsg("支付已关闭");
                    break;
                case "TRADE_SUCCESS":
                    payResultDTO.setStatus(PayStatusEnum.PROCESSED.getCode());
                    payResultDTO.setAmount(new BigDecimal(response.getTotalAmount()));
                    payResultDTO.setMsg("支付成功");
                    //order.setPayStatus(Constants.PAY_STATUS_PAID);
                    // 这里写支付成功的逻辑，例如设置支付时间，订单状态什么的
                    System.out.println("-------------------支付成功");
                    //修改订单状态
                    Order order = new Order();
                    order.setPaystate(0);
                    order.setPaytype(1);
                    order.setIsDeleted(0);
                    order.setTotalprice(new BigDecimal(response.getTotalAmount()).doubleValue());
                    QueryWrapper<Order> wrapper = new QueryWrapper<>();
                    wrapper.eq("orderid",orderId);
//                    wrapper.eq("paystate",1);
                    weiXinMapper.update(order,wrapper);
                    //往支付日志表中添加支付日志信息
                    PayLog payLog = new PayLog();
                    payLog.setOrderid(orderId);
                    payLog.setPayTime(new Date());

                    payLog.setTotalFee(new BigDecimal(response.getTotalAmount()));
                    payLog.setTransactionId(response.getTradeNo());
                    payLog.setTradeState(response.getTradeStatus());
                    payLog.setPayType(1);
                    int insert = payLogMapper.insert(payLog);
                    //查询该订单下的商品信息，修改对应商品的库存
                    QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("orderid",orderId).select("goodsid","goodsnum");
                    List<Order> orderList = orderMapper.selectList(queryWrapper);
                    List<GoodsNumUpdateVo> list = new ArrayList<>();
                    for (Order order1 : orderList) {
                        GoodsNumUpdateVo goodsNumUpdateVo = new GoodsNumUpdateVo();
                        goodsNumUpdateVo.setGoodsid(order1.getGoodsid());
                        goodsNumUpdateVo.setGoodsnum(order1.getGoodsnum());
                        list.add(goodsNumUpdateVo);
                    }
                    //调用feign接口修改商品库存
                    Integer i = goodsFeign.updateGoodsNum(list);
                    break;
                default:
                    break;
            }
            return payResultDTO;
        } catch (AlipayApiException e) {
            payResultDTO.setStatus(-1);
            payResultDTO.setMsg("查询订单状态错误:" + e.getErrMsg());
            return payResultDTO;
        }
    }

}
